package com.sqrj.phoneorder.Controller;

import com.sqrj.phoneorder.Vo.SysUserVo;
import com.sqrj.phoneorder.common.Const;
import com.sqrj.phoneorder.common.HttpClientUtil;
import com.sqrj.phoneorder.common.JsonData;
import com.sqrj.phoneorder.model.*;
import com.sqrj.phoneorder.service.SysUserService;
import com.sqrj.phoneorder.service.WebUserControlService;
import com.sqrj.phoneorder.service.WxOrderUserService;
import com.sqrj.phoneorder.util.RedisOperator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

@RestController
public class WXloginController {

    private Logger logger = LoggerFactory.getLogger(WXloginController.class);
    @Resource
    private WxOrderUserService wxOrderUserService;

    @Resource
    private WebUserControlService webUserControlService;

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    public RedisOperator redis;

    //重新登录
    @RequestMapping("/reload")
    public String reLoad(){
        String dlgq = "reload";
        return dlgq;
    }

    //登录
    @PostMapping("/wxLogin")
    public WxUnitUserVo wxLogin(String code, HttpServletRequest request){
        String url ="https://api.weixin.qq.com/sns/jscode2session";
        Map<String, String> param = new HashMap<String,String>();
        param.put("appid","wx7de6db30ada942bb");
        param.put("secret", "d6b16a67a05f0895fbc76bc5b91c0857");
        param.put("js_code", code);
        param.put("grant_type", "authorization_code");

        String wxresult = HttpClientUtil.doGet(url,param);
        WxOrderUser wxOrderUser = new WxOrderUser();
        String[] wxsz = wxresult.split(",");
        String openId = wxsz[1].substring(wxsz[1].indexOf(":")+2,wxsz[1].length()-2);
        String wxid = openId.substring(openId.length()-10,openId.length()-1);
        logger.info("currentLoginUser:{}",wxid);
        wxOrderUser.setWxid(wxid);
        wxOrderUser.setOpenid(openId);
        String uniqueToken = UUID.randomUUID().toString();
        redis.set(Const.USER_REDIS_SESSION +":"+wxid,uniqueToken,60*30);
        WxUnitUserVo wxUnitUserVo = new WxUnitUserVo();
        BeanUtils.copyProperties(wxOrderUser,wxUnitUserVo);
        wxUnitUserVo.setUserToken(uniqueToken);
        WxOrderUser wxOrderUser1 = wxOrderUserService.login(openId);

        if(wxOrderUser1 != null){
            request.getSession().setAttribute(Const.CURRENT_USER,wxOrderUser1);
            WxUnitUserVo wxUnitUserVo1 = new WxUnitUserVo();
            BeanUtils.copyProperties(wxOrderUser1,wxUnitUserVo1);
            wxUnitUserVo1.setUserToken(uniqueToken);
            return wxUnitUserVo1;
        }else{
            wxOrderUserService.save(wxOrderUser);
            return wxUnitUserVo;
        }

    }

    //企业端登录
    @PostMapping("/wxUnitLogin")
    public JsonData wxUnitLogin(String code, HttpServletRequest request){
        WebUserControl webUserControl = null;
        String url ="https://api.weixin.qq.com/sns/jscode2session";
        Map<String, String> param = new HashMap<String,String>();
        param.put("appid","wx6a1f531d9b868d9c");
        param.put("secret", "4db83efc193c600e66133518762ebaf2");
        param.put("js_code", code);
        param.put("grant_type", "authorization_code");
        String errorMsg = "";
        String wxresult = HttpClientUtil.doGet(url,param);
        System.out.println("session+用户ID"+wxresult);
        String[] wxsz = wxresult.split(",");
        String openId = wxsz[1].substring(wxsz[1].indexOf(":")+2,wxsz[1].length()-2);
        SysUser sysUser = sysUserService.isBindWXbyopenId(openId);
        // code 时间判断 不应为个人
        if(sysUser != null && sysUser.getJbzCode() != null) {
            webUserControl = webUserControlService.findByCode(sysUser.getJbzCode());
        }
        if(sysUser == null) {
            errorMsg = "此微信还未绑定登录账号,请先普通账号登录进入-我的-绑定微信";
            return JsonData.fail(errorMsg);
        }else if (sysUser.getStatus() != 1) {
            errorMsg = "绑定账号已冻结,请联系022-66351935开通";
            return  JsonData.fail(errorMsg);
        }else if ( sysUser.getJbzCode() == null ) {
            errorMsg = "该用户未绑定搅拌站！";
            return  JsonData.fail(errorMsg);
        } else if ((!sysUser.getJbzCode().contains("0000")) && webUserControl == null) {
            errorMsg = "查询不到该用户所属搅拌站，请刷新重试";
            return  JsonData.fail(errorMsg);
        } else if ( (!sysUser.getJbzCode().contains("0000")) && webUserControl.getRemaintime().indexOf('-')>-1) {
            errorMsg = "搅拌站已到期，请联系022-66351935开通";
            return  JsonData.fail(errorMsg);
        }
        else{
            SysUserVo sysUserVo = new SysUserVo();
            sysUserVo.setBindWX(true);
            sysUserVo.setJbzCode(sysUser.getJbzCode());
            return JsonData.success(sysUserVo);
        }


    }

    //企业端用户绑定微信
    @PostMapping("/wxUserbindWX")
    public JsonData wxUnitLogin1(@RequestBody Map<String, Object> map){
        String code = (String)map.get("code");
        String username = (String)map.get("username");
        String url ="https://api.weixin.qq.com/sns/jscode2session";
        Map<String, String> param = new HashMap<String,String>();
        param.put("appid","wx6a1f531d9b868d9c");
        param.put("secret", "4db83efc193c600e66133518762ebaf2");
        param.put("js_code", code);
        param.put("grant_type", "authorization_code");

        String wxresult = HttpClientUtil.doGet(url,param);
        WxOrderUser wxOrderUser = new WxOrderUser();
        String[] wxsz = wxresult.split(",");
        System.out.println( wxsz[1].substring(wxsz[1].indexOf(":")+2,wxsz[1].length()-2));
        String openId = wxsz[1].substring(wxsz[1].indexOf(":")+2,wxsz[1].length()-2);

        SysUser sysUser=sysUserService.findByKeyword(username);
        SysUser sysUserOpenId = sysUserService.isBindWXbyopenId(openId);
        if(sysUser != null && sysUser.getWxopenid() != null){
            return JsonData.fail("该账号已绑定其他微信用户");
        }else if(sysUserOpenId != null){
            return JsonData.fail("该微信已绑定其他账号，暂不支持换绑,可在关于我们中联系我们提此功能增加");
        }else{
           int count =  sysUserService.webUserBindWX(username,openId);
           if(count >0){
               return JsonData.success("绑定成功，可直接点击微信登录");
           }else{
               return  JsonData.fail("绑定失败");
           }
        }


    }
}
